package com.olda.play.auth.security.token;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.olda.play.auth.security.userdetails.web.SysUserDetails;
import com.olda.play.auth.security.userdetails.wechat.WechatUserDetails;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Map;

/**
 * 自定义JwtAccessToken转换器
 */
public class JwtAccessToken extends JwtAccessTokenConverter {

    /**
     * 生成token--并增强信息
     * @param accessToken
     * @param authentication
     * @return
     */
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        DefaultOAuth2AccessToken defaultOAuth2AccessToken = new DefaultOAuth2AccessToken(accessToken);

        Map<String, Object> additionalInfo = MapUtil.newHashMap();
        Object principal = authentication.getUserAuthentication().getPrincipal();

        //todo 系统管理用户认证信息
        if (principal instanceof SysUserDetails) {
            SysUserDetails sysUserDetails = (SysUserDetails) principal;
            additionalInfo.put("userId", sysUserDetails.getUserId());
            additionalInfo.put("username", sysUserDetails.getUsername());
            additionalInfo.put("deptId", sysUserDetails.getDeptId());
            // 认证身份标识(username:用户名；)
            if (StrUtil.isNotBlank(sysUserDetails.getAuthenticationIdentity())) {
                additionalInfo.put("authenticationIdentity", sysUserDetails.getAuthenticationIdentity());
            }
//            additionalInfo.put("userInfo",sysUserDetails);
        } else if (principal instanceof WechatUserDetails) {
            //todo 用户认证信息
            WechatUserDetails wechatUserDetails = (WechatUserDetails) principal;
            additionalInfo.put("memberId", wechatUserDetails.getMemberId());
            additionalInfo.put("username", wechatUserDetails.getUsername());
            // 认证身份标识(mobile:手机号；openId:开放式认证系统唯一身份标识)
            if (StrUtil.isNotBlank(wechatUserDetails.getAuthenticationIdentity())) {
                additionalInfo.put("authenticationIdentity", wechatUserDetails.getAuthenticationIdentity());
            }
        }

        // 将用户信息添加到token额外信息中
        defaultOAuth2AccessToken.setAdditionalInformation(additionalInfo);
        return super.enhance(defaultOAuth2AccessToken, authentication);
    }
}
